package com.vend.common.log
import android.os.Environment
import com.elvishew.xlog.LogLevel
import com.elvishew.xlog.XLog
import com.elvishew.xlog.flattener.Flattener
import com.elvishew.xlog.flattener.Flattener2
import com.elvishew.xlog.printer.file.FilePrinter
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy
import com.elvishew.xlog.printer.file.clean.FileLastModifiedCleanStrategy
import java.io.File
import java.text.SimpleDateFormat

/**
 * Created by glendal on 2022/1/14.
 * 日志初始化
 */
object LogInit {
    var logStr = "/vendApp"
    var maxData = 15

    /**
     * 初始化日志
     */
    fun initLog() {
        logStr
        val parentPath =
            Environment.getExternalStorageDirectory().toString() + logStr + File.separator
        val file = File(parentPath)
        if (!file.exists()) {
            file.mkdir()
        }
        val filePrinter = FilePrinter.Builder(parentPath) // 指定保存日志文件的路径
            .fileNameGenerator(MyDateFileNameGenerator()) // 指定日志文件名生成器，默认为 ChangelessFileNameGenerator("log")
            .backupStrategy(NeverBackupStrategy()) // 指定日志文件备份策略，默认为 FileSizeBackupStrategy(1024 * 1024)
            .cleanStrategy(FileLastModifiedCleanStrategy((maxData * 24 * 60 * 60 * 1000).toLong())) // 指定日志文件清除策略，默认为 NeverCleanStrategy()
            .flattener(MyFlattener())
            .build()
        XLog.init(LogLevel.ALL, filePrinter);
    }

    /**
     * 自定了日志过滤
     */
    class MyFlattener : Flattener2, Flattener {
        override fun flatten(logLevel: Int, tag: String?, message: String?): CharSequence? {
            return tag?.let {
                message?.let { it1 ->
                    flatten(
                        System.currentTimeMillis(), logLevel, it,
                        it1
                    )
                }
            }
        }

        override fun flatten(
            timeMillis: Long,
            logLevel: Int,
            tag: String,
            message: String
        ): CharSequence? {
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") //设置格式
            val timeText = format.format(timeMillis)
            return ("$timeText  $message")
        }
    }

    /**
     * 设置日志路径
     */
    fun setLogStrSrc(str : String){
        this.logStr = str
    }

    /**
     * 设置保留日志的最大天数
     */
    fun setLogMaxData(number : Int){
        this.maxData = number
    }

}